<?php
/**
 * @Author: xuzhiyi
 * @Date:   2016-02-16 20:57:17
 * @Last Modified by:   xuzhiyi
 * @Last Modified time: 2016-02-29 17:08:04
 * ------------------------------------------------ *
 * 品牌管理                                          *
 * ------------------------------------------------ */
 namespace Admin\Model;

class BrandsModel extends CommonModel {
 
//新增

	 public function addBrands(){
	 	$ids = I("catId");
		$data = array();
		$data["brandName"] = I("brandName");
		
		$data["brandDesc"] = I("brandDesc");
		$data["createTime"] = date('Y-m-d H:i:s');
		$data["brandFlag"] = 1;
		if($this->checkEmpty($data) && count($ids)>0){
			if(!empty($_FILES['brandIco']['tmp_name'])){
				$brandIco=$this->upAvatar('brandIco');
				if($brandIco==false){
					return false;
				}
				$data["brandIco"] = $brandIco;
			}
			//$data["brandIco"] = I("brandIco");

			$m = M('brands');
			$rs = $m->add($data);
		    if(false !== $rs){
		        $m = M('goods_cat_brands');
				foreach ($ids as $key =>$v){
					$d = array();
					$d['catId'] = $v;
					$d['brandId'] = $rs;
					$m->add($d);
				}
				return true;
			}
			if(!empty($brandIco)){
				$this->delAvatar($brandIco);
			}
		}
		return flase;
	 } 
 
//修改

	 public function editBrands(){
	 	$brandId = (int)I("brandId",0);
	 	$oldBrandIco=M('brands')->where("brandId=".$brandId)->getField('brandIco');
	 	$ids = I("catId");
	    
	 	$filter = array();
	 	//获取品牌的关联分类
	 	$catBrands=M('goods_cat_brands')->where("brandId=".$brandId)->getField('catId');
		foreach ($catBrands as $key =>$v){
			if(!in_array($v['catId'],$ids))$filter[] = $v['catId'];
		}
		//查询指定的分类下是否有品牌被引用了
		
		if(count($filter)>0){
			$filter = implode(',',$filter);
			$count=M(goods)->where("brandId =".$brandId." and goodsCatId1 in(".$filter.")")->count();
			if($count>0){				
				return false;
			}
		}
		$m = M('brands');
		$m->brandName = I("brandName");
		
		$m->brandDesc = I("brandDesc");
	    if($this->checkEmpty($data) && count($ids)>0){
	    	if(!empty($_FILES['brandIco']['tmp_name'])){
				$brandIco=$this->upAvatar('brandIco');
				if($brandIco==false){
					return false;
				}
				$m->brandIco = $brandIco;
			}

			$rs = $m->where("brandId=".$brandId)->save();
			if(false !== $rs){
			    $cm = M('goods_cat_brands');
				$cm->where('brandId='.$brandId)->delete();
			    foreach ($ids as $key =>$v){
					$d = array();
					$d['catId'] = $v;
					$d['brandId'] = $brandId;
					$cm->add($d);
				}
				if(!empty($oldBrandIco) && !empty($BrandIco)){
					$this->delAvatar($oldBrandIco);
				}
				return true;
			}
		}
		if(!empty($brandIco)){
			$this->delAvatar($brandIco);
		}

		return false;
	 } 


	  

//删除

	 public function delBrands(){
	 	$m = M('brands');
	 	$m->brandFlag = -1;
	 	$rs = $m->where("brandId=".(int)I('brandId',0))->save();
	    if(false !== $rs){
			return true;
		}
		return false;
	 }
}